package cloud.mist.sailonix.service;

import cloud.mist.sailonix.common.ResultCode;
import cloud.mist.sailonix.entity.User;
import cloud.mist.sailonix.exception.BusinessException;
import cloud.mist.sailonix.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserMapper userMapper;

    /**
     * 保存用户
     */
    public User saveUser(User user) {
        // 参数校验
        validateUser(user);
        
        // 检查用户名是否已存在
        if (isUsernameExists(user.getUsername())) {
            throw BusinessException.of(ResultCode.USERNAME_DUPLICATE);
        }
        
        // 设置创建和更新时间
        if (user.getCreateTime() == null) {
            user.setCreateTime(LocalDateTime.now());
        }
        user.setUpdateTime(LocalDateTime.now());
        
        try {
            userMapper.insert(user);
            log.info("用户创建成功: {}", user.getUsername());
            return user;
        } catch (Exception e) {
            log.error("用户创建失败: {}", e.getMessage(), e);
            throw BusinessException.of(ResultCode.DATABASE_ERROR, "用户创建失败");
        }
    }

    /**
     * 根据ID查询用户
     */
    public User getUserById(Long id) {
        if (id == null || id <= 0) {
            throw BusinessException.of(ResultCode.BAD_REQUEST, "用户ID不能为空或小于等于0");
        }
        
        User user = userMapper.selectById(id);
        if (user == null) {
            throw BusinessException.of(ResultCode.USER_NOT_FOUND);
        }
        
        log.info("查询用户成功: {}", user.getUsername());
        return user;
    }

    /**
     * 查询所有用户
     */
    public List<User> getAllUsers() {
        try {
            List<User> users = userMapper.selectList(new QueryWrapper<>());
            log.info("查询所有用户成功，共{}个", users.size());
            return users;
        } catch (Exception e) {
            log.error("查询所有用户失败: {}", e.getMessage(), e);
            throw BusinessException.of(ResultCode.DATABASE_ERROR, "查询用户列表失败");
        }
    }

    /**
     * 根据用户名查询
     */
    public List<User> getUsersByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            throw BusinessException.of(ResultCode.BAD_REQUEST, "用户名不能为空");
        }
        
        try {
            List<User> users = userMapper.selectList(new QueryWrapper<User>().like("username", username));
            log.info("根据用户名{}查询用户成功，共{}个", username, users.size());
            return users;
        } catch (Exception e) {
            log.error("根据用户名查询用户失败: {}", e.getMessage(), e);
            throw BusinessException.of(ResultCode.DATABASE_ERROR, "查询用户失败");
        }
    }

    /**
     * 批量保存用户
     */
    public void batchSaveUsers(List<User> users) {
        if (users == null || users.isEmpty()) {
            throw BusinessException.of(ResultCode.BAD_REQUEST, "用户列表不能为空");
        }
        
        // 验证每个用户
        for (User user : users) {
            validateUser(user);
        }
        
        try {
            users.forEach(this::saveUser);
            log.info("批量创建用户成功，共{}个", users.size());
        } catch (Exception e) {
            log.error("批量创建用户失败: {}", e.getMessage(), e);
            throw BusinessException.of(ResultCode.DATABASE_ERROR, "批量创建用户失败");
        }
    }

    /**
     * 统计用户数量
     */
    public Long countUsers() {
        try {
            Long count = userMapper.selectCount(new QueryWrapper<>());
            log.info("统计用户数量成功: {}", count);
            return count;
        } catch (Exception e) {
            log.error("统计用户数量失败: {}", e.getMessage(), e);
            throw BusinessException.of(ResultCode.DATABASE_ERROR, "统计用户数量失败");
        }
    }

    /**
     * 验证用户信息
     */
    private void validateUser(User user) {
        if (user == null) {
            throw BusinessException.of(ResultCode.BAD_REQUEST, "用户信息不能为空");
        }
        
        if (!StringUtils.hasText(user.getUsername())) {
            throw BusinessException.of(ResultCode.BAD_REQUEST, "用户名不能为空");
        }
        
        if (user.getUsername().length() > 50) {
            throw BusinessException.of(ResultCode.BAD_REQUEST, "用户名长度不能超过50个字符");
        }
        
        if (StringUtils.hasText(user.getEmail()) && user.getEmail().length() > 100) {
            throw BusinessException.of(ResultCode.BAD_REQUEST, "邮箱长度不能超过100个字符");
        }
        
        if (StringUtils.hasText(user.getPhone()) && user.getPhone().length() > 20) {
            throw BusinessException.of(ResultCode.BAD_REQUEST, "手机号长度不能超过20个字符");
        }
        
        if (user.getAge() != null && (user.getAge() < 0 || user.getAge() > 150)) {
            throw BusinessException.of(ResultCode.BAD_REQUEST, "年龄必须在0-150之间");
        }
    }

    /**
     * 检查用户名是否已存在
     */
    private boolean isUsernameExists(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.selectCount(queryWrapper) > 0;
    }
}